package updatahomework;

import java.util.Scanner;

/**
 * @classname:Exception2
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/7 17:14
 * @version: 0.1
 * @since:1.8
 */
public class Exception2 {
    public static Goods[] goods;
    public static Scanner input;

    static {
        goods = new Goods[3];
        input = new Scanner(System.in);
        goods[0] = new Goods(1,"apple", 10, 8000);
        goods[1] = new Goods(2,"apple", 5, 3500);
        goods[2] = new Goods(3,"apple", 8, 4200);
    }

    public static void main(String[] args) {

            buygood();

    }

    private static void buygood() {
        showGoods();
        System.out.println("请输入要买的商品id");
        int goodId = input.nextInt();
        Goods buygood = null;
        boolean flag = false;
        for (Goods good : goods) {
            if(good==null){
                break;
            }
            if(good.getId() == goodId){
                buygood = good;
                flag = true;
                break;
            }
        }
        if(!flag){
            throw new BuyGoodsException("商品不存在");
        }
        System.out.println("您购买的商品信息如下");
        System.out.println(buygood);
        System.out.println("请输入要购买"+buygood.getName()+"的数量");

        int buynum = input.nextInt();

        if(buynum>buygood.getStore()){
            throw new BuyGoodsException("该商品库存不足");
        }
        System.out.println("购买"+buygood.getName()+buynum+"个"+"共计"+buynum*buygood.getPrice());
        buygood.setStore(buygood.getStore()-buynum);
        showGoods();



    }

    private static void showGoods() {
        for (Goods good : goods) {
            if (good != null) {
                System.out.println(good);
            }
        }
    }

}
